{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "from PIL import Image, ImageDraw\n",
    "\n",
    "def round_corners(image_path, output_path, corner_radius=90):\n",
    "    # 打开原始图片\n",
    "    img = Image.open(image_path).convert(\"RGBA\")\n",
    "    \n",
    "    # 创建一个新的带有透明背景的图片\n",
    "    width, height = img.size\n",
    "    mask = Image.new('L', (width, height), 0)\n",
    "    \n",
    "    # 绘制圆角\n",
    "    draw = ImageDraw.Draw(mask)\n",
    "    draw.rounded_rectangle([(0, 0), (width, height)], corner_radius, fill=255)\n",
    "    \n",
    "    # 将原图片和圆角mask结合\n",
    "    output = Image.new('RGBA', (width, height), (0, 0, 0, 0))\n",
    "    output.paste(img, (0, 0), mask)\n",
    "    \n",
    "    # 保存结果\n",
    "    output.save(output_path)\n",
    "\n",
    "def crop_to_circle(input_path, output_path):\n",
    "    # 打开原始图片\n",
    "    img = Image.open(input_path).convert(\"RGBA\")\n",
    "    \n",
    "    # 获取图片尺寸\n",
    "    width, height = img.size\n",
    "    \n",
    "    # 计算正方形裁剪区域的大小和位置\n",
    "    size = min(width, height)\n",
    "    left = (width - size) // 2\n",
    "    top = (height - size) // 2\n",
    "    right = left + size\n",
    "    bottom = top + size\n",
    "    \n",
    "    # 裁剪图片为正方形\n",
    "    img = img.crop((left, top, right, bottom))\n",
    "    \n",
    "    # 创建一个正方形画布作为遮罩\n",
    "    mask = Image.new('L', (size, size), 0)\n",
    "    \n",
    "    # 绘制白色圆形\n",
    "    draw = ImageDraw.Draw(mask)\n",
    "    draw.ellipse((0, 0, size, size), fill=255)\n",
    "    \n",
    "    # 创建输出图像\n",
    "    output = Image.new('RGBA', (size, size), (0, 0, 0, 0))\n",
    "    \n",
    "    # 将裁剪后的图片与圆形遮罩结合\n",
    "    output.paste(img, (0, 0), mask)\n",
    "    \n",
    "    # 保存结果\n",
    "    output.save(output_path)\n",
    "\n",
    "# 使用示例\n",
    "input_image = \"/Users/allwefantasy/Downloads/我的头像_rounded.jpg\"\n",
    "output_image = \"/Users/allwefantasy/Downloads/圆角头像.png\"\n",
    "crop_to_circle(input_image, output_image)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "byzerllm",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
